// @ts-nocheck
const express = require("express")
const app = express()
//引入session中间件
const session = require("express-session")
//将session配置到app.use上
app.use(session({
	secret: 'keyboard cat',
	resave: false, 
	saveUninitialized: true
}))
app.use(express.urlencoded({ extended: false }))
//需要通过静态资源托管来设置cookic 直接通过跨域是无法设置的
app.use(express.static("../public"))
app.post("/api/login", (req, res) => {
    if (req.body.username !== "admin" || req.body.password !== "000000") {
        return res.send({
            status: 1, msg: "登录失败!!"
        })
    }
    //将登录成功的用户信息保存到session中
    req.session.user = req.body
    req.session.islogin = true
    res.send({
        status: 0,
        msg: "登录成功" + req.session.user.username + req.session.islogin
    })
})

app.get("/api/username", (req, res) => {
    if (!req.session.islogin) {
        return res.send({ status: 1, msg: "fail" })
    }
    res.send({
        status: 0, msg: "succsee", username: req.session.user.username
    })
})

app.get("/api/logout",(req,res)=>{
    req.session.destroy()
    res.send({
        status:0,
        msg:"退出成功"
    })
})

app.listen(8080)